﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_OuterRequestNoteRelationService: IPurchase_OuterRequestNoteRelationService
    {
        private List<Purchase_OuterRequestNoteRelation> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_OuterRequestNoteRelation>(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey);
                if (List != null && List.Count > 0)
                    return List;

                List = DapperDbContext.Query<Purchase_OuterRequestNoteRelation>("select * from [Purchase_OuterRequestNoteRelation] where Status != @Status", new { Status = Status.delete }).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_OuterRequestNoteRelation>();
        }
        public List<Purchase_OuterRequestNoteRelation> GetListByNoteId(int NoteId)
        {
            return Init().Where(x => x.OuterNoteId == NoteId).ToList();
        }
        public List<Purchase_OuterRequestNoteRelation> GetListByRequestId(int RequestId)
        {
            return Init().Where(x => x.OuterRequestId == RequestId).ToList();
        }
        public int Save(Purchase_OuterRequestNoteRelation ent, UserCache user)
        {
            IDbModelService<Purchase_OuterRequestNoteRelation> db = new DbModelService<Purchase_OuterRequestNoteRelation>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (ent.Id == 0)
                    {
                        ent.Create(user);
                        var noteid = db.InsertOne(ent, conn, transaction);
                        ent.Id = noteid;

                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, noteid, ent);
                        transaction.Commit();
                        return noteid;
                    }
                    else
                    {
                        ent.Modify(user);
                        db.UpdateById(ent, conn, transaction);
                        transaction.Commit();
                        if (ent != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, ent.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, ent.Id, ent);
                        }
                        return ent.Id;
                    }

                }
            }

            catch (Exception ex)
            {

                transaction.Rollback();
                return -1;
            }
        }
        public List<Purchase_OuterRequestNoteRelation> GetRelationListByNoteId(int NoteId)
        {
            return Init().Where(x => x.OuterNoteId == NoteId).ToList();
        }
        public List<Purchase_OuterRequestNoteRelation> GetRelationListByNoteIds(List<int> NoteIds)
        {
            return Init().Where(x => NoteIds.Contains(x.OuterNoteId)).ToList();
        }
        public List<Purchase_OuterRequestNoteRelation> GetRelationListByRequestIds(List<int> RequestIds)
        {
            return Init().Where(x => RequestIds.Contains(x.OuterRequestId)).ToList();
        }
        public int DeleteByRequestIdAndNoteId(int RequestId, int NoteId,UserCache userinfo)
        {
            List<int> ids = Init().Where(x => x.OuterRequestId == RequestId && x.OuterNoteId == NoteId).Select(x=>x.Id).Distinct().ToList();
            using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
            {
                string sql = "UPDATE [dbo].[Purchase_OuterRequestNoteRelation] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
                int delcount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = userinfo.UserId, LastUpdateTime = DateTime.Now, Id = ids });
                if (delcount > 0)
                {
                    foreach (var id in ids)
                    {
                        RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, id.ToString());
                    }
                }
                return delcount;
            }
        }
        public void UpdateExpectMoney(int Id, decimal ExpectMoney,int OuterNum,UserCache UserInfo)
        {
            //DbModelService<Purchase_OuterRequestNoteRelation> db
            IDbModelService<Purchase_OuterRequestNoteRelation> db = new DbModelService<Purchase_OuterRequestNoteRelation>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    Purchase_OuterRequestNoteRelation entity = Init().Find(x => x.Id == Id);
                    entity.Modify(UserInfo);
                    entity.ExpectMoney = ExpectMoney;
                    entity.OuterNum = OuterNum;
                    db.UpdateById(entity, conn, transaction);
                    transaction.Commit();
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, entity.Id.ToString());
                    RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, entity.Id, entity);
                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
            }
        }
        public void UpdateRealMoney(int NoteId,decimal RealMoney,UserCache userCache,decimal SingleMoney)
        {
            List<Purchase_OuterRequestNoteRelation> list = Init().Where(x => x.OuterNoteId == NoteId).ToList();

            IDbModelService<Purchase_OuterRequestNoteRelation> db = new DbModelService<Purchase_OuterRequestNoteRelation>();
            IDbTransaction transaction = null;
            using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
            {
                transaction = conn.BeginTransaction();
                foreach (var entity in list)
                {
                    entity.RealMoney = Math.Round(entity.OuterNum * SingleMoney,2);
                    db.UpdateById(entity, conn, transaction);
                }
                transaction.Commit();
                foreach(var entity in list)
                {
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, entity.Id.ToString());
                    RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestNoteRelationCacheKey, entity.Id, entity);
                }
            }
            
        }
        public Purchase_OuterRequestNoteRelation GetDetail(int Id)
        {
            return Init().Where(x => x.Id == Id).FirstOrDefault();
        }
        public Purchase_OuterRequestNoteRelation GetDetailByRequestIdAndNoteId(int RequestId, int NoteId)
        {
            return Init().Where(x => x.OuterRequestId == RequestId&&x.OuterNoteId==NoteId).FirstOrDefault();
        }
    }
}
